import axios from 'axios'

import {
	getToken,
	removeToken
} from '@/utils/auth'
import config from '@/utils/config'

import {
	Dialog
} from "vant";

// create an axios instance
const service = axios.create({
	baseURL: config.baseURL,
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 500000 // request timeout
})

// request interceptor
service.interceptors.request.use(
	config => {
		// do something before request is sent
		if (config.method) {
			config.params = {
				...config.params
			}
		}
		if(getToken()) {
			config.headers['authorization'] = `Bearer ${getToken()}`
		}
		if (config.method === 'post' ||
			config.method === 'put' ||
			config.method === 'delete') {
			config.data = {
				...config.data
			}
		}
		return config
	},
	error => {
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	response => {
		const res = response.data
		// if the custom code is not 200, it is judged as an error.
		if (res.code == 0) {
			// 提示
			// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
			if (res.msg == 'Must have token') {
				removeToken()
				location.reload()
				return
			}
			Dialog.alert({
				title: "提示",
				message: res.msg,
			}).then(() => {});
			return Promise.reject(new Error(res.msg || 'Error'))
		} else {
			return res
		}
	},
	error => {
		if(/401/.test(error)) {
			removeToken()
			location.reload()
		}
		if(/500/.test(error)) {
			// 提示
		}
		return Promise.reject(error)
	}
)

export default service
